package cn.pzhu.javaee.mybook.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.pzhu.javaee.mybook.context.MybookConstant;
import cn.pzhu.javaee.mybook.dao.UserDao;
import cn.pzhu.javaee.mybook.domain.User;
import cn.pzhu.javaee.webapp.servlet.WebAppBaseServlet;

/**
 * Servlet implementation class AuthServlet
 */
@WebServlet("/auth")
public class AuthServlet extends WebAppBaseServlet {
	private static final long serialVersionUID = 1L;
	private UserDao udao=new UserDao();
	public void actionLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.debug("actionLogin....");
		String loginName=this.getString(request, "loginName");
		String password=this.getString(request, "password");
		log.debug("loginName:{},password:{}",loginName,password);
		String errmsg=null;
		if(loginName!=null&&password!=null){
			User user=udao.findByLoginName(loginName);
			if(user!=null){
				if(password.equals(user.getPassword())){
					log.debug("{} 登录成功",loginName);
					HttpSession session=request.getSession();
					session.setAttribute(MybookConstant.SESSION_NAME_CUR_USER,user);
					this.redirect(response, "mybook?action=list");
				}else{
					errmsg="密码不匹配";
				}
			}else{
				errmsg="用户名"+loginName+"不存在";
			}
		}else{
			errmsg="必须输入用户和密码";
		}
		if(errmsg!=null){
			request.setAttribute("ERROR_MSG", errmsg);
			String loginUrl="login.jsp";
			this.forward(request, response, loginUrl);
		}
		
	}

	public void actionLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.debug("actionLogout....");
		HttpSession session=request.getSession();
		session.removeAttribute(MybookConstant.SESSION_NAME_CUR_USER);
		String loginUrl=request.getContextPath()+"/login.jsp";
		this.redirect(response, loginUrl);
	}

}
